<template>
  <div>
    <h2>欢迎{{ user.uname }}！您的 uid 为{{ user.uid }}</h2>
    <el-button @click="getUserList">获取用户列表</el-button>
    <el-button type="danger" @click="logout">登出</el-button>
    
    <div v-if="userList.length > 0" style="margin-top: 20px;">
      <h3>用户列表：</h3>
      <el-table :data="userList" style="width: 100%">
        <el-table-column prop="uid" label="用户ID" width="180"></el-table-column>
        <el-table-column prop="uname" label="用户名" width="180"></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: {
        uname: "",
        uid: null,
      },
      userList: []
    };
  },
  methods: {
    logout(){
      // 清除localStorage中的token和用户信息
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      this.$router.push('/login');
    },
    getUserList() {
      this.$request({
        url: "/user/selectAll",
        method: "get"
      }).then(res => {
        if (res.code === "0") {
          this.userList = res.data;
        } else {
          this.$message.error(res.msg);
        }
      }).catch(err => {
        console.error(err);
      });
    }
  },
  mounted() {
    // 从localStorage获取用户信息
    if (localStorage.getItem('userInfo')) {
      this.user = JSON.parse(localStorage.getItem('userInfo'));
    } else {
      // 如果没有用户信息，跳转到登录页
      this.$router.push('/login');
    }
  },
};
</script>

<style scoped>
</style>